package com.threeonemeeting.util;

import java.util.Date;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;

import com.snda.lib.http.ICallBack;
import com.snda.lib.http.TaskManager;
import com.snda.lib.ui.MessageBox;
import com.snda.lib.util.FileHelper;
import com.snda.lib.util.IntentHelper;
import com.snda.lib.util.MiscHelper;
import com.snda.lib.util.TimeHelper;
import com.snda.lib.util.UIHelper;
import com.threeonemeeting.Const;
import com.threeonemeeting.DataCenter;
import com.threeonemeeting.MeetingApplication;
import com.threeonemeeting.R;
import com.threeonemeeting.db.AppDBHelper;
import com.threeonemeeting.list.CityInfoList;
import com.threeonemeeting.list.DepartmentInfoList;
import com.threeonemeeting.list.PosInfoList;
import com.threeonemeeting.list.TradesInfoList;
import com.threeonemeeting.tab.BaseTabActivity;
import com.threeonemeeting.tab.MultiActivityTab;
import com.threeonemeeting.task.GetCityListTask;
import com.threeonemeeting.task.GetDepartmentListTask;
import com.threeonemeeting.task.GetMeetingTradesListTask;
import com.threeonemeeting.task.GetPosStatusListTask;

public class MiscUtil {

	public static MeetingApplication getApp(Context context) {
		return (MeetingApplication) context.getApplicationContext();
	}

	public static void openDocument(Activity ac, String strApkPath) {
		if (strApkPath == null)
			return;

		if (FileHelper.isExistFile(strApkPath) == false)
			return;

		Intent intent = IntentHelper.getOpenFileIntent(strApkPath);
		if (intent == null)
			return;

		MultiActivityTab tabActivity = (MultiActivityTab) ac.getParent();
		try {
			if (tabActivity != null) {
				tabActivity.startActivity(intent);
			} else {
				ac.startActivity(intent);
			}
		} catch (ActivityNotFoundException e) {
			MessageBox.showToast(ac.getApplicationContext(), "无法打开该类型文件");
		}
	}

	public static String getBetweenTime(String strBeginTime, String strEndTime) {
		Date beginTime = TimeHelper.stringToDate(strBeginTime, null);
		Date endTime = TimeHelper.stringToDate(strEndTime, null);

		if (beginTime != null && endTime != null) {
			// 如果开始日期和截至日期是在同一天
			if (beginTime.getDay() == endTime.getDay()) {

				String strMonth = String.valueOf(beginTime.getMonth() + 1);
				if (strMonth.length() == 1)
					strMonth = "0" + strMonth;

				String strDay = String.valueOf(beginTime.getDate());
				if (strDay.length() == 1)
					strDay = "0" + strDay;

				String strBeginHours = String.valueOf(beginTime.getHours());
				if (strBeginHours.length() == 1)
					strBeginHours = "0" + strBeginHours;

				String strBeginMinutes = String.valueOf(beginTime.getMinutes());
				if (strBeginMinutes.length() == 1)
					strBeginMinutes = "0" + strBeginMinutes;

				String strEndHours = String.valueOf(endTime.getHours());
				if (strEndHours.length() == 1)
					strEndHours = "0" + strEndHours;

				String strEndMinutes = String.valueOf(endTime.getMinutes());
				if (strEndMinutes.length() == 1)
					strEndMinutes = "0" + strEndMinutes;

				String strTime = (beginTime.getYear() + 1900) + "年" + strMonth
						+ "月" + strDay + "日 " + strBeginHours + ":"
						+ strBeginMinutes + "-" + strEndHours + ":"
						+ strEndMinutes;
				return strTime;

			} else if (beginTime.getYear() == endTime.getYear()) {

				String strBeginMonth = String.valueOf(beginTime.getMonth() + 1);
				if (strBeginMonth.length() == 1)
					strBeginMonth = "0" + strBeginMonth;

				String strBeginDay = String.valueOf(beginTime.getDate());
				if (strBeginDay.length() == 1)
					strBeginDay = "0" + strBeginDay;

				String strEndMonth = String.valueOf(endTime.getMonth() + 1);
				if (strEndMonth.length() == 1)
					strEndMonth = "0" + strEndMonth;

				String strEndDay = String.valueOf(endTime.getDate());
				if (strEndDay.length() == 1)
					strEndDay = "0" + strEndDay;

				String strTime = (beginTime.getYear() + 1900) + "年"
						+ strBeginMonth + "月" + strBeginDay + "日 " + "-"
						+ strEndMonth + "月" + strEndDay + "日 ";
				return strTime;

			} else {
				String strTime = TimeHelper.dateToString(beginTime,
						"yyyy年MM月dd日")
						+ "-"
						+ TimeHelper.dateToString(endTime, "yyyy年MM月dd日");
				return strTime;
			}
		} else if (beginTime != null) {
			return strBeginTime;
		} else if (endTime != null) {
			return strEndTime;
		}

		return "";
	}

	/**
	 * 删除input字符串中的html格式
	 * 
	 * @param input
	 * @param length
	 * @return
	 */
	public static String splitAndFilterString(String input, int length) {
		if (input == null || input.trim().equals("")) {
			return "";
		}
		// 去掉所有html元素,
		String str = input.replaceAll("\\&[a-zA-Z]{1,10};", "").replaceAll(
				"<[^>]*>", "");
		str = str.replaceAll("[(/>)<]", "");
		int len = str.length();
		if (len <= length) {
			return str;
		} else {
			str = str.substring(0, length);
			str += "......";
		}
		return str;
	}

	/**
	 * @desc 检查城市的数据是否已经存在，如果不存在，则拉取
	 * @param context
	 */
	public static boolean checkCity(Context context, ICallBack cb) {
		CityInfoList listCity = DataCenter.getInstance().listCity;
		if (listCity == null || listCity.size() == 0) {
			AppDBHelper db = DataCenter.getInstance().db;
			listCity = db.getAllCitys();
		}

		if (listCity.size() == 0) {
			// 获取城市列表
			GetCityListTask getcitytask = new GetCityListTask(context, cb);
			TaskManager.addTask(getcitytask, null, false);
			return false;
		}

		DataCenter.getInstance().listCity = listCity;
		return true;
	}

	/**
	 * @desc 检查本地部门的数据是否已经存在，如果不存在，则拉取
	 * @param context
	 */
	public static boolean checkDepartment(Context context, ICallBack cb) {
		DepartmentInfoList listDepts = DataCenter.getInstance().listDeptInfo;
		if (listDepts == null || listDepts.size() == 0) {
			AppDBHelper db = DataCenter.getInstance().db;
			listDepts.listDepartmentInfo = db.getAllDepts();
		}

		if (listDepts.size() == 0) {
			GetDepartmentListTask task = new GetDepartmentListTask(context, cb);
			TaskManager.addTask(task, null, false);
			return false;
		}

		DataCenter.getInstance().listDeptInfo = listDepts;
		return true;
	}

	/**
	 * @desc 检查职位的数据是否已经存在，如果不存在，则拉取
	 * @param context
	 */
	public static boolean checkPosStatus(Context context, ICallBack cb) {
		PosInfoList listPos = DataCenter.getInstance().listPosInfo;
		if (listPos == null || listPos.size() == 0) {
			AppDBHelper db = DataCenter.getInstance().db;
			listPos.listPosInfo = db.getAllPos();
		}

		if (listPos.size() == 0) {
			GetPosStatusListTask task = new GetPosStatusListTask(context, cb);
			TaskManager.addTask(task, null, false);
			return false;
		}

		DataCenter.getInstance().listPosInfo = listPos;
		return true;
	}

	/**
	 * @desc 检查行业的数据是否已经存在，如果不存在，则拉取
	 * @param context
	 */
	public static boolean checkTradesInfo(Context context, ICallBack cb) {
		TradesInfoList listTrades = DataCenter.getInstance().listTrades;
		if (listTrades == null || listTrades.size() == 0) {
			AppDBHelper db = DataCenter.getInstance().db;
			listTrades = db.getAllTrades();
		}

		if (listTrades.size() == 0) {
			GetMeetingTradesListTask task = new GetMeetingTradesListTask(
					context, cb);
			TaskManager.addTask(task, null, false);
			return false;
		}

		DataCenter.getInstance().listTrades = listTrades;
		return true;
	}

	/**
	 * 图片异步渲染 + 本地代理缓存
	 * 
	 * @param imageView
	 * @param imageUrl
	 */
	public static void setImageView(ImageView imageView, String strImageUrl) {

		Context context = DataCenter.getInstance().getApplicationContext();
		if (context == null)
			return;

		String strCachedDir = AppSettings.getImagePath(context);
		UIHelper.setImageView(context, imageView, strImageUrl, strCachedDir);
	}

	/**
	 * 将dp转换成px
	 * 
	 * @param context
	 * @param dipValue
	 * @return
	 */
	public static int dp2px(float dipValue) {
		Context context = DataCenter.getInstance().getApplicationContext();
		if (context == null)
			return 0;

		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (dipValue * scale + 0.5f);
	}

	/**
	 * 将px转换成dp
	 * 
	 * @param context
	 * @param pxValue
	 * @return
	 */
	public static int px2dp(float pxValue) {
		Context context = DataCenter.getInstance().getApplicationContext();
		if (context == null)
			return 0;

		final float scale = context.getResources().getDisplayMetrics().density;
		return (int) (pxValue / scale + 0.5f);
	}

	/**
	 * 设置存储名称
	 * 
	 * @param context
	 * @param name
	 * @param val
	 * @return
	 */
	public static boolean setPrefer(String strKeyName, String strKeyValue) {
		Context context = DataCenter.getInstance().getApplicationContext();
		if (context == null)
			return false;

		return MiscHelper.setPrefer(context, Const.Pref.PREFS_NAME, strKeyName,
				strKeyValue);
	}

	/**
	 * 获取存储名称的值
	 * 
	 * @param strKeyName
	 * @return
	 */
	public static String getPrefer(String strKeyName) {
		Context context = DataCenter.getInstance().getApplicationContext();
		if (context == null)
			return null;

		return MiscHelper.getPrefer(context, Const.Pref.PREFS_NAME, strKeyName);
	}

	public static Bitmap getDocTypeBitmapByName(String strFileName) {
		int nIndex = strFileName.lastIndexOf('.');
		if (nIndex != -1) {
			String strExtName = strFileName.substring(nIndex + 1,
					strFileName.length());
			return MiscUtil.getDocTypeBitmap(strExtName);
		} else {
			return MiscUtil.getDocTypeBitmap("tmp");
		}
	}

	/**
	 * 根据类型获取对应的图标
	 * 
	 * @param strType
	 * @return
	 */
	public static Bitmap getDocTypeBitmap(String strType) {
		Context context = DataCenter.getInstance().getApplicationContext();
		if (context == null)
			return null;

		// 检查是否是doc文件
		if (strType.equalsIgnoreCase("doc") == true) {
			return BitmapFactory.decodeResource(context.getResources(),
					R.drawable.doc);
		}
		// 检查是否是ppt文件
		else if (strType.equalsIgnoreCase("ppt") == true) {
			return BitmapFactory.decodeResource(context.getResources(),
					R.drawable.ppt);

		}
		// 检查是否是ppt文件
		else if (strType.equalsIgnoreCase("xls") == true) {
			return BitmapFactory.decodeResource(context.getResources(),
					R.drawable.xls);

		}
		// 检查是否是pdf文件
		else if (strType.equalsIgnoreCase("pdf") == true) {
			return BitmapFactory.decodeResource(context.getResources(),
					R.drawable.pdf);

		}
		// 检查是否是mp3文件
		else if (strType.equalsIgnoreCase("mp3") == true) {
			return BitmapFactory.decodeResource(context.getResources(),
					R.drawable.mp3);

		}
		// 检查是否是wav文件
		else if (strType.equalsIgnoreCase("wav") == true) {
			return BitmapFactory.decodeResource(context.getResources(),
					R.drawable.wav);
		}

		return BitmapFactory.decodeResource(context.getResources(),
				R.drawable.document);
	}

	public static void showLoadingLayout(Activity ac) {
		LinearLayout loadingLayout = (LinearLayout) ac
				.findViewById(R.id.loading_layout);
		LinearLayout listLayout = (LinearLayout) ac
				.findViewById(R.id.list_layout);
		LinearLayout noRecordLayout = (LinearLayout) ac
				.findViewById(R.id.norecord_layout);
		loadingLayout.setVisibility(View.VISIBLE);
		listLayout.setVisibility(View.GONE);
		noRecordLayout.setVisibility(View.GONE);
	}

	public static void showLoadingLayout(Activity ac, String strLoadingText) {
		LinearLayout loadingLayout = (LinearLayout) ac
				.findViewById(R.id.loading_layout);
		LinearLayout listLayout = (LinearLayout) ac
				.findViewById(R.id.list_layout);
		LinearLayout noRecordLayout = (LinearLayout) ac
				.findViewById(R.id.norecord_layout);
		loadingLayout.setVisibility(View.VISIBLE);
		listLayout.setVisibility(View.GONE);
		noRecordLayout.setVisibility(View.GONE);

		TextView txHint = (TextView) ac.findViewById(R.id.loading_text);
		txHint.setText(strLoadingText);
	}

	public static void showListLayout(Activity ac, int nSize) {
		LinearLayout loadingLayout = (LinearLayout) ac
				.findViewById(R.id.loading_layout);
		LinearLayout norecordLayout = (LinearLayout) ac
				.findViewById(R.id.norecord_layout);
		LinearLayout listLayout = (LinearLayout) ac
				.findViewById(R.id.list_layout);
		loadingLayout.setVisibility(View.GONE);

		if (nSize == 0) {
			norecordLayout.setVisibility(View.VISIBLE);
			listLayout.setVisibility(View.GONE);
			return;
		}

		norecordLayout.setVisibility(View.GONE);
		listLayout.setVisibility(View.VISIBLE);
	}

	public static void showListLayout(Activity ac, int nSize, String strHintText) {
		LinearLayout loadingLayout = (LinearLayout) ac
				.findViewById(R.id.loading_layout);
		LinearLayout norecordLayout = (LinearLayout) ac
				.findViewById(R.id.norecord_layout);
		LinearLayout listLayout = (LinearLayout) ac
				.findViewById(R.id.list_layout);
		loadingLayout.setVisibility(View.GONE);

		if (nSize == 0) {
			norecordLayout.setVisibility(View.VISIBLE);
			listLayout.setVisibility(View.GONE);
			return;
		}

		norecordLayout.setVisibility(View.GONE);
		listLayout.setVisibility(View.VISIBLE);

		TextView txHint = (TextView) ac.findViewById(R.id.norecord_textview);
		txHint.setText(strHintText);
	}

	// 返回
	public static void setBackBtnListener(final BaseTabActivity activity) {
		Button btnBack = (Button) activity.findViewById(R.id.back);
		if (btnBack != null) {
			btnBack.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					activity.back();
				}
			});
		}
	}

	// 返回
	public static void setTitle(final BaseTabActivity activity, String strTitle) {
		TextView txTitle = (TextView) activity.findViewById(R.id.title);
		if (txTitle != null) {
			txTitle.setText(strTitle);
		}
	}

	public static void setListViewHeight(ListView lv) {
		ListAdapter la = lv.getAdapter();
		if (null == la) {
			return;
		}

		// calculate height of all items.
		int h = 0;
		final int cnt = la.getCount();
		for (int i = 0; i < cnt; i++) {
			View item = la.getView(i, null, lv);
			item.measure(0, 0);
			h += item.getMeasuredHeight();
		}

		// reset ListView height
		ViewGroup.LayoutParams lp = lv.getLayoutParams();
		lp.height = h + (lv.getDividerHeight() * (cnt - 1));
		lv.setLayoutParams(lp);
	}

}